/*
 * Copyright 2008 ZXing authors
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.google.zxing.oned;

import java.util.Hashtable;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.WriterException;
import com.google.zxing.common.ByteMatrix;
import com.google.zxing.oned.Code39Reader;
import android.util.Log;

/**
 * This object renders a CODE39 code as a ByteMatrix 2D array of greyscale
 * values.
 * 
 * @author erik.barbara@gmail.com (Erik Barbara)
 */
public class Code39Writer extends AbstractUPCEANWriter {

	  public ByteMatrix encode(String contents, BarcodeFormat format, int width, int height,
	      Hashtable hints) throws WriterException {
	    if (format != BarcodeFormat.CODE_39) {
	      throw new IllegalArgumentException("Can only encode CODE_39, but got " + format);
	    }
	    
	    return super.encode(contents, format, width, height, hints);
	  }

	  public byte[] encode(String contents) {
	    if (contents.length() > 80) {
	      throw new IllegalArgumentException(
	          "Requested contents should be less than 80 digits long, but got " + contents.length());
	    }
	    int codeWidth=24+contents.length()+1;
	    for(int i=0;i<contents.length();i++)
	    {
	    	int indexInString=Code39Reader.ALPHABET_STRING.indexOf(contents.charAt(i));
	    	int[] intArray=toIntArray(Code39Reader.CHARACTER_ENCODINGS[indexInString]);
	    	for(int j=0;j<intArray.length;j++)
	    		codeWidth+=intArray[j];
	    }
	    byte[] result = new byte[codeWidth];
	    int pos = 0;
	    int[] narrowWhite=new int[]{1};
	    pos+=appendPattern(result,pos,toIntArray(Code39Reader.CHARACTER_ENCODINGS[39]),1);
	    pos+=appendPattern(result,pos,narrowWhite,0);
	    //append next character to bytematrix
	    for(int i=contents.length()-1;i>-1;i--)
	    {
	    	int indexInString=Code39Reader.ALPHABET_STRING.indexOf(contents.charAt(i));
	    	int[] intArray=toIntArray(Code39Reader.CHARACTER_ENCODINGS[indexInString]);
	    	pos+= appendPattern(result,pos,intArray,1);
	    	pos+=appendPattern(result,pos,narrowWhite,0);
	    }
	    pos+=appendPattern(result,pos,toIntArray(Code39Reader.CHARACTER_ENCODINGS[39]),1);
	    return result;
	  }
	  
	  private int[] toIntArray(int a)
	  {
		  int[] toReturn=new int[9];
		  for(int i=0;i<9;i++)
		  {
			  int temp=a & (int)Math.pow(2,i);
			  if(temp==0)
				  toReturn[i]=1;
			  else
				  toReturn[i]=2;
		  }
		  return toReturn;
	  }
}